from elasticsearch import Elasticsearch
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from house.models import House, House_city

es = Elasticsearch("http://8.154.26.188:9200")

#定义索引名称
house_index_name = "house"

#创建索引
for index_name,mappings in [
    (house_index_name,{
        "mappings":{
            "properties":{
                "id":{"type":"integer"},
                "title":{"type":"text"},#房屋标题
                "city":{"type":"text"},#分类城市
                "city_id":{"type":"integer"},#城市id
                "city_pid":{"type":"integer"},#城市父类id
                "price":{"type":"float"},#价格
            }
        }
    })
]:
    if not es.indices.exists(index=index_name):
        es.indices.create(index=index_name,body=mappings)
        print(f"索引{index_name}创建成功")


# #数据同步类视图
class DataSyncView(APIView):
    def get(self, request):
        #同步房源和城市数据（合并展示）
        house_data = House.objects.all()
        city_data= House_city.objects.all()
        #构建分类字典
        city_dict = {i.id: i.city for i in city_data}

        for item in house_data:
            es.index(index=house_index_name, id=item.id, body={
                "id": item.id, #房屋id
                "title": item.title, #房屋标题
                "city": city_dict.get(item.city_id,''), #分类城市
                "pid": item.city_id, #城市id
                "city_pid": item.city_pid_id, #城市父类id
                "price": item.price, #价格
            })
        return Response({"message": "数据同步成功"},status=status.HTTP_200_OK)


#搜索视图
class SearchView(APIView):
    def get(self, request):
        #获取搜索关键字
        title_condition = request.GET.get('title','')#房屋标题
        house_min_price= request.GET.get('house_min_price')#房屋最低价格
        house_max_price= request.GET.get('house_max_price')#房屋最高价格
        house_page = int(request.GET.get('house_page',1))#当前页
        house_page_size = int(request.GET.get('house_page_size',10))#每页显示条数

        #构建查询DSL
        house_condition = []
        #城市和房源查询条件
        if title_condition:
            house_condition.append({"match": {"title": title_condition}})
        if house_min_price or house_max_price:
            price_range = {}
            if house_min_price:
                price_range["gte"] = int(house_min_price)
            if house_max_price:
                price_range["lte"] = int(house_max_price)
            house_condition.append({"range": {"price": price_range}})

        #查询所有数据的条件
        house_query={"query": {"bool": {"must": house_condition}}} if house_condition else {"query": {"match_all": {}}}
        #分页
        house_query["from"] = (house_page - 1) * house_page_size
        house_query["size"] = house_page_size

        results={}
        #执行查询
        try:
            #查询elasticsearch
            house_response = es.search(index=house_index_name, body=house_query)
            house_hits = house_response["hits"]["hits"]
            house_results= [hit["_source"] for hit in house_hits]
            results={"house_results":house_results}
            return Response({
                "total":{
                    "count":house_response["hits"]["total"]["value"],#总条数
                },
                "page":{
                    "current":house_page,#当前页
                },
                "page_size":{
                    "size":house_page_size,#每页显示条数
                },
                "data":results
            },status=status.HTTP_200_OK)
        except Exception as e:
            return Response({"message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)






